<template>
	<div class="coupon-detail" v-loading="loading">
		<ProdTreeSelector v-model="dialogVisible" :keyword="detailItem.searchKeyword" @getSkuList="getSkuList" />
		<el-form ref="ruleFormRef" :model="detailItem" :rules="rules" label-width="120px" class="demo-ruleForm">
			<el-form-item label="商品名称" prop="name">
				<el-input style="width: 400px" v-model="detailItem.name" placeholder="请输入商品名称" maxlength="200" />
			</el-form-item>
			<el-form-item label="商品介绍">
				<el-row>
					<el-col :span="24" style="margin-bottom: 10px">
						<el-button type="success" :icon="Plus" @click="addIntroduction()">添加介绍</el-button>
					</el-col>
					<el-col
						:span="24"
						v-for="(item, index) in detailItem.introductionList"
						:key="`detail-introduction-item-${index}`"
						style="margin-bottom: 10px"
					>
						<el-input style="width: 400px" v-model="item.name" placeholder="请输入产品概述" maxlength="200" />
						<el-button type="danger" :icon="Delete" circle @click="delIntroduction(index)" style="margin-left: 10px"></el-button>
					</el-col>
				</el-row>
			</el-form-item>
			<el-form-item label="规格">
				<el-button type="success" :icon="Plus" @click="addPriceItem()">添加规格</el-button>
				<el-table :data="detailItem.specificationsList" style="width: 100%">
					<el-table-column label="规格名称-可编辑">
						<template #default="scope">
							<el-input v-model="scope.row.name" placeholder="请输入规格名称" maxlength="200" />
						</template>
					</el-table-column>
					<el-table-column label="规格值-可编辑">
						<template #default="scope">
							<el-input v-model="scope.row.value" placeholder="请输入规格值" maxlength="200" />
						</template>
					</el-table-column>
					<el-table-column label="价格-可编辑">
						<template #default="scope">
							<el-input-number :min="0" :max="MAX_LENGTH" controls-position="right" v-model="scope.row.price"></el-input-number>
						</template>
					</el-table-column>
					<el-table-column width="50px">
						<template #default="scope">
							<el-button type="danger" :icon="Delete" circle @click="delPriceItem(scope.$index)"></el-button>
						</template>
					</el-table-column>
				</el-table>
			</el-form-item>
			<div class="detail-price-table"></div>
			<el-form-item label="关联站点">
				<el-select style="width: 200px" v-model="detailItem.associatedSite" placeholder="选择站点">
					<el-option v-show="item.value !== 'all'" v-for="item in siteOptions" :key="item.value" :label="item.label" :value="item.value"></el-option>
				</el-select>
			</el-form-item>
			<el-form-item label="关联商品">
				<div class="use-list">
					<div class="use-item">
						<div class="left-radio-box">
							<el-radio :disabled="importLoading" @change="clearTagsAndProductList()" v-model="detailItem.useRadio" :label="USE_GOODS_1">
								<span></span>
							</el-radio>
						</div>
						<div class="center-content">
							<div class="center-content-p">全部商品</div>
						</div>
						<div class="right-btn" v-if="detailItem.useRadio === USE_GOODS_1">
							<el-button @click="addType(`all`)">添加</el-button>
						</div>
					</div>
					<div class="use-item">
						<div class="left-radio-box">
							<el-radio :disabled="importLoading" @change="clearTagsAndProductList()" v-model="detailItem.useRadio" :label="USE_GOODS_2">
								<span></span>
							</el-radio>
						</div>
						<div class="center-content">
							<div class="center-content-input">
								<CateSelector v-model="detailItem.classificationId" />
							</div>
						</div>
						<div class="right-btn" v-if="detailItem.useRadio === USE_GOODS_2">
							<el-button @click="addType()">添加</el-button>
						</div>
					</div>
					<div class="use-item">
						<div class="left-radio-box">
							<el-radio :disabled="importLoading" @change="clearTagsAndProductList()" v-model="detailItem.useRadio" :label="USE_GOODS_3">
								<span></span>
							</el-radio>
						</div>
						<div class="center-content">
							<div class="center-content-input">
								<el-input v-model="detailItem.searchKeyword" placeholder="搜索商品" maxlength="200" @keyup.enter="searchProduct()" />
							</div>
						</div>
						<div class="right-btn" v-if="detailItem.useRadio === USE_GOODS_3">
							<el-button @click="searchProduct()">添加</el-button>
						</div>
					</div>
					<div class="use-item">
						<div class="left-radio-box">
							<el-radio :disabled="importLoading" @change="clearTagsAndProductList()" v-model="detailItem.useRadio" :label="USE_GOODS_4">
								<span></span>
							</el-radio>
						</div>
						<div class="center-content">
							<div class="center-content-input">
								<el-input
									v-model="detailItem.importKeyword"
									placeholder="批量导入：请输入商品名称用“，”隔开"
									maxlength="500"
									@keyup.enter="batchImport()"
								/>
							</div>
						</div>
						<div class="right-btn" v-if="detailItem.useRadio === USE_GOODS_4">
							<el-button @click="batchImport()" :loading="importLoading">添加</el-button>
						</div>
					</div>
				</div>
			</el-form-item>
			<el-form-item label="已添加" v-if="detailItem.tags.length > 0">
				<el-tag class="coupon-detail-tag" v-for="tag in detailItem.tags" @close="closeTag(tag)" :key="tag.name" closable type="success">{{
					tag.name
				}}</el-tag>
			</el-form-item>
			<div class="coupon-detail-table" v-if="detailItem.selectProductList.length > 0">
				<div class="coupon-detail-table-header">
					<div class="coupon-detail-table-header-left">
						<el-checkbox v-model="checkAll" :indeterminate="isIndeterminate" @change="handleCheckAllChange">全选</el-checkbox>
					</div>
					<div class="coupon-detail-table-header-right">
						<el-link type="primary" @click="delSelectProductList()">删除</el-link>
					</div>
				</div>
				<el-table v-loading="loading" :data="detailItem.selectProductList" style="width: 100%">
					<el-table-column label show-overflow-tooltip width="50px">
						<template #default="scope">
							<el-checkbox v-model="scope.row.isChecked" @change="handleCheckedCitiesChange" label></el-checkbox>
						</template>
					</el-table-column>
					<el-table-column prop="orderNumber" label="序号" show-overflow-tooltip width="80px"></el-table-column>
					<el-table-column prop="name" label="商品名称" show-overflow-tooltip></el-table-column>
					<el-table-column label="商品图片" width="100" show-overflow-tooltip>
						<template #default="scope">
							<el-image lazy :src="scope.row.imgUrl" :preview-src-list="srcList" :initial-index="scope.$index"></el-image>
						</template>
					</el-table-column>
					<el-table-column label="商品原价" show-overflow-tooltip>
						<template #default="scope">
							<span v-html="scope.row.originalPrice"></span>
						</template>
					</el-table-column>
					<el-table-column prop="sku" label="自编SKU" show-overflow-tooltip></el-table-column>
				</el-table>
			</div>
			<!-- <div class="coupon-detail-btns">
				<el-button @click="cancel()" :loading="submitLoading">取消</el-button>
				<el-button type="primary" @click="submitForm()" :loading="submitLoading">保存</el-button>
			</div> -->
		</el-form>
	</div>
</template>

<script setup>
import { Delete, Plus } from '@element-plus/icons-vue';
import { ElMessage } from 'element-plus';
import { siteOptions } from '/@/stores/cityList';
import CateSelector from '/@/components/common/CateSelector.vue';
import useServiceState from '/@/utils/pageState/serviveState';
import { cateFormat } from '/@/utils/filters';
import { isEmpty } from '/@/utils';
import { getCommonSiteList } from '/@/utils/commonRequest';
import { useCouponApi } from '/@/api/coupon';
import { useServiceApi } from '/@/api/service';
import ProdTreeSelector from '/@/components/common/prodTreeSelector/ProdTreeSelector.vue';

const { getPriceByField, MAX_LENGTH, USE_GOODS_1, USE_GOODS_2, USE_GOODS_3, USE_GOODS_4 } = useServiceState();
const { getSkuListByName } = useCouponApi();
const { addAfterSaleGoods, updateAfterSaleGoods, getAfterSaleGoodsDetail } = useServiceApi();

const props = defineProps({
	couponId: {
		type: Number,
		default: -1,
	},
});
const emit = defineEmits(['update:couponId', 'reloadList']);
const ruleFormRef = ref(null);
let loading = ref(false);
let submitLoading = ref(false);
let dialogVisible = ref(false);
let isReady = ref(false);
let importLoading = ref(false);
let checkAll = ref(false);
let isIndeterminate = ref(false);
let srcList = ref([]);
let cityList = ref([]);
let detailItem = ref({
	id: '',
	name: '',
	introductionList: [{ name: '' }],
	specificationsList: [returnNewSpecificationsItem()],
	associatedSite: 'US',
	useRadio: USE_GOODS_1,
	classificationId: 0,
	searchKeyword: '',
	importKeyword: '',
	tags: [],
	selectProductList: [],
});
let rules = {
	name: [
		{
			required: true,
			message: '请输入商品名称',
			trigger: 'blur',
		},
	],
};

init();
function init() {
	getCityList();
	if (props.couponId === 0) {
		return;
	}
	getDetail();
}

async function getDetail() {
	loading.value = true;
	try {
		let params = {
			id: props.couponId,
		};
		let res = await getAfterSaleGoodsDetail(params.id);
		if (res.code !== 200) {
			loading.value = false;
			// ElMessage({
			//     type: "error",
			//     message: res.data.msg,
			// });
			return;
		}
		let tempItem = res.data;
		let tags = [],
			selectProductList = [],
			introductionList = [],
			specificationsList = [];

		if (tempItem.productCategoryList !== null) {
			tags = tempItem.productCategoryList.map((ceil) => {
				return {
					id: ceil.id,
					name: ceil.name,
				};
			});
			tags = Array.from(new Set([...tags]));
		}

		if (tempItem.useType === USE_GOODS_1) {
			tags = [
				{
					id: 0,
					name: '全部商品',
				},
			];
		}

		if (tempItem.skuStockList !== null) {
			selectProductList = tempItem.skuStockList.map((ceil, index) => {
				return {
					id: ceil.id,
					isChecked: false,
					orderNumber: index + 1,
					name: ceil.productName,
					imgUrl: ceil.pic,
					originalPrice:
						getPriceByField(ceil.euPrice, 'euPrice') +
						'<br/>' +
						getPriceByField(ceil.ukPrice, 'ukPrice') +
						'<br/>' +
						getPriceByField(ceil.usPrice, 'usPrice'),
					sku: ceil.skuCode,
					frequency: ceil.limitNum,
				};
			});
		}

		if (tempItem.detailDesc !== null) {
			let tempList = tempItem.detailDesc.split('，，');
			introductionList = tempList.map((ceil) => {
				return { name: ceil };
			});
		}

		if (tempItem.afterSaleProductAttrList !== null) {
			specificationsList = tempItem.afterSaleProductAttrList.map((ceil) => {
				return {
					id: ceil.id,
					name: ceil.attrName,
					value: ceil.attrValue,
					// 这里三个价格全都一样，不做关联
					price: ceil.ukPrice ? ceil.ukPrice : 0,
				};
			});
		}

		detailItem.value = {
			id: tempItem.id,
			name: tempItem.name,
			introductionList,
			specificationsList,
			associatedSite: tempItem.site,
			useRadio: tempItem.useType,
			classificationId: 0,
			searchKeyword: '',
			importKeyword: '',
			tags,
			selectProductList,
		};
		loading.value = false;
		isReady.value = true;
	} catch (error) {
		loading.value = false;
		console.error(error);
		ElMessage({
			type: 'error',
			message: '获取详情失败',
		});
	}
}

async function getCityList() {
	try {
		cityList.value = await getCommonSiteList();
	} catch (error) {
		console.log('error', error);
	}
}

function submitForm() {
	ruleFormRef.value.validate((valid) => {
		if (valid) {
			// alert('submit!')
			submit();
		} else {
			// console.log("error submit!!")
			return false;
		}
	});
}

async function submit() {
	submitLoading.value = true;
	console.log(props.couponId);
	try {
		let params = {};
		let res = null;
		const item = detailItem.value;

		let afterSaleProductAttrList = [],
			detailDescList = [],
			detailDesc = '',
			categoryIdList = [],
			afterSaleSkuRelationList = [],
			isErr = false;

		if (isErr) {
			submitLoading.value = false;
			ElMessage({
				type: 'info',
				message: '消费满的值不得大于订单减少的值！',
			});
			return;
		}

		afterSaleProductAttrList = item.specificationsList.map((ceil) => {
			return {
				id: ceil.id,
				attrName: ceil.name,
				attrValue: ceil.value,
				euPrice: ceil.price ? ceil.price : 0,
				ukPrice: ceil.price ? ceil.price : 0,
				usPrice: ceil.price ? ceil.price : 0,
			};
		});

		detailDescList = item.introductionList.map((ceil) => {
			return ceil.name;
		});
		detailDesc = detailDescList.join('，，');

		categoryIdList = item.tags.map((ceil) => {
			return ceil.id;
		});
		categoryIdList = Array.from(new Set([...categoryIdList]));

		if (item.useRadio === USE_GOODS_1) {
			categoryIdList = [];
		}
		afterSaleSkuRelationList = item.selectProductList.map((ceil) => {
			return {
				skuId: ceil.id,
				skuCode: ceil.sku,
			};
		});

		// 新增
		if (props.couponId === 0) {
			params = {
				name: item.name,
				afterSaleProductAttrList,
				detailDesc,
				site: item.associatedSite,
				// 下方
				useType: item.useRadio,
				categoryIdList,
				afterSaleSkuRelationList,
			};
			res = await addAfterSaleGoods(params);
		}
		// 修改
		else {
			params = {
				id: props.couponId,
				name: item.name,
				afterSaleProductAttrList,
				detailDesc,
				site: item.associatedSite,
				// 下方
				useType: item.useRadio,
				categoryIdList,
				afterSaleSkuRelationList,
			};
			res = await updateAfterSaleGoods(params);
		}

		if (res.code !== 200) {
			submitLoading.value = false;
			// ElMessage({
			//     type: "error",
			//     message: res.data.msg,
			// });
			return;
		}
		submitLoading.value = false;
		ElMessage({
			type: 'success',
			message: '保存成功！',
		});
		emit('reloadList');
		cancel();
	} catch (error) {
		console.log('error', error);
		submitLoading.value = false;
		ElMessage({
			type: 'error',
			message: '保存失败',
		});
	}
}

function cancel() {
	emit('update:couponId', -1);
}

function addType(params) {
	if (params) {
		if (detailItem.value.tags.length === 1) {
			ElMessage({
				type: 'info',
				message: '全部商品类型只能添加一次',
			});
			return;
		}

		detailItem.value.tags.push({ name: '全部商品', id: 'params' });
		return;
	}
	let classificationId = detailItem.value.classificationId;
	if (isEmpty(classificationId) || classificationId === 0) {
		return;
	}
	detailItem.value.tags.push({ name: `${cateFormat(classificationId)}`, id: classificationId });
	detailItem.value.tags = duplicateRemovalById(detailItem.value.tags);
}

function closeTag(tag) {
	detailItem.value.tags.splice(detailItem.value.tags.indexOf(tag), 1);
}

function clearTagsAndProductList() {
	detailItem.value.tags = [];
	detailItem.value.selectProductList = [];
}
function searchProduct() {
	if (detailItem.value.useRadio !== USE_GOODS_3) {
		return;
	}
	// 去打开搜索商品的弹窗
	dialogVisible.value = true;
}

// 搜索到的列表的回调
let getSkuList = (skuList) => {
	console.log('777', skuList);
	let tempSelectProductList = [];
	tempSelectProductList = skuList.map((ceil, index) => {
		return {
			id: ceil.id,
			isChecked: false,
			orderNumber: detailItem.value.selectProductList.length + index + 1,
			name: ceil.productName,
			imgUrl: ceil.pic,
			originalPrice:
				getPriceByField(ceil.euPrice, 'euPrice') +
				'<br/>' +
				getPriceByField(ceil.ukPrice, 'ukPrice') +
				'<br/>' +
				getPriceByField(ceil.usPrice, 'usPrice'),
			sku: ceil.skuCode,
			frequency: MAX_LENGTH,
		};
	});
	detailItem.value.selectProductList = [...detailItem.value.selectProductList, ...tempSelectProductList];
	detailItem.value.selectProductList = duplicateRemovalById(detailItem.value.selectProductList);
	importLoading.value = false;
};

function batchImport() {
	if (detailItem.value.useRadio !== USE_GOODS_4 || importLoading.value) {
		return;
	}
	let text = detailItem.value.importKeyword;
	if (isEmpty(text)) {
		ElMessage({
			type: 'info',
			message: '请输入商品名称用“，”隔开',
		});
		return;
	}
	batchImportFun();
}

async function batchImportFun() {
	importLoading.value = true;
	try {
		let params = {
			name: detailItem.value.importKeyword,
		};
		let res = await getSkuListByName(params);
		if (res.code !== 200) {
			importLoading.value = false;
			// ElMessage({
			//     type: "error",
			//     message: res.data.msg,
			// });
			return;
		}
		if (res.data.length === 0) {
			importLoading.value = false;
			ElMessage({
				type: 'info',
				message: '暂无商品',
			});
			return;
		}
		let tempList = res.data.data.map((item, index) => {
			return {
				id: item.id,
				isChecked: false,
				orderNumber: detailItem.value.selectProductList.length + index + 1,
				name: item.productName,
				imgUrl: item.pic,
				originalPrice:
					getPriceByField(item.euPrice, 'euPrice') +
					'<br/>' +
					getPriceByField(item.ukPrice, 'ukPrice') +
					'<br/>' +
					getPriceByField(item.usPrice, 'usPrice'),
				sku: item.skuCode,
				frequency: MAX_LENGTH,
			};
		});
		if (tempList.length > 0) {
			checkAll.value = false;
		}
		detailItem.value.selectProductList = [...detailItem.value.selectProductList, ...tempList];
		detailItem.value.selectProductList = duplicateRemovalById(detailItem.value.selectProductList);
		setSrcList(detailItem.value.selectProductList);
		importLoading.value = false;
	} catch (error) {
		importLoading.value = false;
		console.error(error);
		ElMessage({
			type: 'error',
			message: '搜索商品失败',
		});
	}
}

function setSrcList(list) {
	srcList.value = list.map((item) => {
		return item.imgUrl ? item.imgUrl : '';
	});
}

function setAllChecked(state) {
	let productList = detailItem.value.selectProductList;
	let tempList = productList.map((item) => {
		item.isChecked = state;
		return item;
	});
	detailItem.value.selectProductList = tempList;
}

function delSelectProductList() {
	let productList = detailItem.value.selectProductList;
	let newList = productList.filter((item) => {
		if (!item.isChecked) {
			return item;
		}
	});
	detailItem.value.selectProductList = newList;
}

function handleCheckAllChange(val) {
	console.log('val', val);
	isIndeterminate.value = false;
	setAllChecked(val);
}

function handleCheckedCitiesChange(val) {
	console.log(val);
	let productList = detailItem.value.selectProductList;
	let checkedCount = 0;
	productList.map((item) => {
		if (item.isChecked) {
			checkedCount++;
		}
	});
	checkAll.value = checkedCount === productList.length;
	isIndeterminate.value = checkedCount > 0 && checkedCount < productList.length;
}

function duplicateRemovalById(list) {
	if (list.length === 0) {
		return [];
	}
	let newList = [];
	for (let i = 0; i < list.length; i++) {
		for (var j = i + 1; j < list.length; j++) {
			if (list[i].id == list[j].id) {
				++i;
			}
		}
		newList.push(list[i]);
	}
	return newList;
}

// 获取空的价格item
function returnNewSpecificationsItem() {
	return {
		id: '',
		name: '',
		value: '',
		price: 0,
	};
}

// 新增价格
function addPriceItem() {
	let item = returnNewSpecificationsItem();
	detailItem.value.specificationsList.push(item);
}

// 删除价格
function delPriceItem(index) {
	detailItem.value.specificationsList.splice(index, 1);
}

// 新增产品介绍
function addIntroduction() {
	detailItem.value.introductionList.push({ name: '' });
}

// 删除产品介绍
function delIntroduction(index) {
	detailItem.value.introductionList.splice(index, 1);
}
defineExpose({
	cancel,
	submitForm,
});
</script>

<style lang="scss" scoped>
.coupon-detail {
	max-width: 1200px;
	margin: 0 auto;

	.detail-title {
		font-size: 24px;
		margin: 20px 0;
		display: flex;
		align-items: center;
		svg {
			color: red;
		}
	}
	.detail-introduction-p {
		font-size: 14px;
		display: block;
		width: 100%;
	}
	.detail-introduction-list {
		display: block;
		width: 100%;
		.detail-introduction-item {
			display: flex;
			margin-bottom: 10px;
			.detail-introduction-input {
			}
			.detail-introduction-add {
				margin-left: 10px;
			}
		}
	}
	.detail-price-table-add {
		margin-top: 10px;
		// margin-left: 120px;
	}
	.coupon-detail-btns {
		display: flex;
		align-items: center;
		justify-content: center;
		margin-top: 20px;
	}
	.coupon-detail-tag {
		margin-right: 10px;
	}
	.full-minus-list {
		width: 80 * 2 + 160 * 4 + 30+ 0px;
		display: flex;
		flex-direction: column;
		.full-minus-header {
			width: 100%;
			display: flex;
			.full-minus-header-p {
				display: flex;
				justify-content: flex-end;
				&:nth-child(1) {
					width: 80+160+160+0px;
					padding-right: 20px;
				}
				&:nth-child(2) {
					width: 80+160px;
					padding-right: 20px;
				}
				&:nth-child(3) {
					flex: 1;
					padding-right: 10+30px;
				}
			}
		}
		.full-minus-item {
			display: flex;
			width: 100%;
			margin-bottom: 10px;
			.text-box {
				width: 80px;
				padding-right: 10px;
				text-align: center;
			}
			.input-box {
				width: 160px;
				display: flex;
				padding-right: 10px;
				.input-currency {
					padding-right: 5px;
				}
			}
		}
		.delete-box {
			width: 30px;
			margin-top: 8px;
			color: red;
			display: flex;
			justify-content: center;
			cursor: pointer;
		}
	}
	.discount-list {
		width: 80 * 3 + 160 * 3 + 30 + 0px;
		display: flex;
		flex-direction: column;
		.discount-header {
			width: 100%;
			display: flex;
			.discount-header-p {
				display: flex;
				justify-content: flex-end;
				&:nth-child(1) {
					width: 80+160+80+0px;
					padding-right: 15px;
				}
				&:nth-child(2) {
					width: 80+160px;
					padding-right: 30px;
				}
				&:nth-child(3) {
					flex: 1;
					padding-right: 10+30px;
				}
			}
		}
		.discount-item {
			display: flex;
			width: 100%;
			margin-bottom: 10px;
			.text-box {
				width: 80px;
				padding-right: 10px;
				text-align: center;
			}
			.input-box {
				width: 160px;
				display: flex;
				padding-right: 10px;
				.input-currency {
					padding-left: 5px;
				}
			}
		}
		.delete-box {
			width: 30px;
			margin-top: 8px;
			color: red;
			display: flex;
			justify-content: center;
			cursor: pointer;
		}
	}
	.use-list {
		width: 100%;
		.use-item {
			display: flex;
			width: 100%;
			margin-bottom: 10px;
			.left-radio-box {
			}
			.center-content {
				min-width: 400px;
				.center-content-p {
				}
				.center-content-input {
					width: 100%;
				}
			}
			.right-btn {
				margin-left: 20px;
			}
		}
	}
	.coupon-detail-table-header {
		display: flex;
		align-items: center;
		justify-content: center;
		padding-bottom: 10px;
		.coupon-detail-table-header-left {
			flex: 1;
		}
		.coupon-detail-table-header-right {
			width: 100px;
			text-align: right;
		}
	}
}
</style>
